package com.zerox.springsecuritydemo329.config;

import com.zerox.springsecuritydemo329.filter.JwtAuthenticationTokenFilter;
import com.zerox.springsecuritydemo329.handler.AccessDeniedHandlerImpl;
import com.zerox.springsecuritydemo329.handler.AuthenticationEntryPointImpl;
import com.zerox.springsecuritydemo329.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * spring security 配置
 */

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
//WebSecurityConfigurerAdapter
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandlerImpl;

    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPointImpl;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 关闭csrf 跨站请求伪造,前后端分离项目 就得 关闭
        http.csrf().disable();

        //禁用springsecurity的会话管理
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 给相关请求放行
        http.authorizeRequests().antMatchers("/doLogin","/index.html","/statics/*").permitAll();

        // 任何请求都要认证才能访问
        http.authorizeRequests((requests) -> requests.anyRequest().authenticated());

        // 把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //设置 授权异常和认证异常实现方式
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandlerImpl).authenticationEntryPoint(authenticationEntryPointImpl);
    }

    /**
     * 登录时需要AuthenticationManager对象，正好父类有提供
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
    /**
     * 密码加密
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }


}
